package com.dqhl.community.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.ShopCartAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.GoodsNumberSerializableMap;
import com.dqhl.community.model.ShopCartBean;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * description: 购物车
 * autour: guanluocang
 * date: 2016/10/18 15:01
 */
public class ShoppingCartActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private List<ShopCartBean> list_data;
    private ListView mListView;
    private ShopCartAdapter adapter;

    private RelativeLayout rlRefresh;
    private TextView tvRefresh;
    private ProgressBar barRefresh;
    private LinearLayout clear;
    private CheckBox checkBox_select_all;
    private TextView integral_sum;
    private int sum = 0;
    private int[] sumIntegral;
    private Context context;
    private TextView tv_checkout;
    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private String listData = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        initView();
        getListData();
    }

    private void initView() {
        context = this;
//        showpage = 1;
//        isPermitFlag = true;
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText("购物车");
        list_data = new ArrayList<ShopCartBean>();
        integral_sum = (TextView) findViewById(R.id.integral_sum);
        clear = (LinearLayout) findViewById(R.id.clear);
        checkBox_select_all = (CheckBox) findViewById(R.id.checkbox_select);
        mListView = (ListView) findViewById(R.id.finance_list);
        tv_checkout = (TextView) findViewById(R.id.tv_checkout);
        tv_checkout.setOnClickListener(this);
        clear.setOnClickListener(this);
        checkBox_select_all.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        ivTopBack.setOnClickListener(this);

        if (sum == 1) {
            toast("暂无商品");
            checkBox_select_all.setChecked(false);
            checkBox_select_all.setClickable(false);
        } else {
            checkBox_select_all.setChecked(false);
            checkBox_select_all.setClickable(true);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            //删除
            case R.id.clear:
                Dlog.e(" GG购物车数据!!  " + sum);
                if (sum == 1) {
                    toast("暂无商品");
                } else {
                    doClear();
                }
                break;
            //全选
            case R.id.checkbox_select:
                if (sum == 1) {
                    toast("暂无商品");
                    checkBox_select_all.setChecked(false);
                } else {
                    HashMap<Integer, Boolean> isSelected = ShopCartAdapter.getIsSelected();
                    Iterator iterator = isSelected.entrySet().iterator();
                    List<Boolean> array = new ArrayList<Boolean>();//列表中checkbox选中状态
                    List<Integer> nums = new ArrayList<Integer>();//列表中商品数量
                    while (iterator.hasNext()) {
                        HashMap.Entry entry = (HashMap.Entry) iterator.next();
                        Integer key = (Integer) entry.getKey();
                        Boolean val = (Boolean) entry.getValue();
                        array.add(val);
                    }
                    for (int i = 0; i < list_data.size(); i++) {
                        int num = list_data.get(i).getNumber();
                        double integral = Double.valueOf(list_data.get(i).getPrice());
                        nums.add(num);
                    }
                    if (checkBox_select_all.isChecked()) {

                        for (int i = 0; i < list_data.size(); i++) {
                            ShopCartAdapter.getIsSelected().put(i, true);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < list_data.size(); i++) {
                            ShopCartAdapter.getIsSelected().put(i, false);
                        }
                        adapter.notifyDataSetChanged();
                        integral_sum.setText(0 + "");
                    }
                }
                break;
            case R.id.tv_checkout: //结算
                if (sum == 1) {
                    toast("暂无商品");
                    checkBox_select_all.setChecked(false);
                } else {
                    doCheckOut();
                }
                break;
        }
    }

    /**
     * 清空购物车
     */
    private void doClear() {
        showCustomLoadBar("删除中");
        final List<String> list_clear = new ArrayList<>();
        for (int i = 0; i < list_data.size(); i++) {
            if (ShopCartAdapter.getIsSelected().get(i)) {
                list_clear.add(list_data.get(i).getId());
            }
        }
        Dlog.e("GGlist_clear.toString()" + list_clear.toString());
        if (list_clear.size() == 0) {
            hideCustomLoadBar();
            toast("请选择要删除的项");
        } else {
            RequestParams params = new RequestParams(Config.Api.supermarketCartDel);
            params.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
            params.addBodyParameter("goods", list_clear.toString()); //商品ID 为json格式数组
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 0) {
                        for (int i = 0; i < list_data.size(); i++) {
                            if (ShopCartAdapter.getIsSelected().get(i)) {
                                list_data.remove(list_data.get(i));
                            }
                        }
                        adapter.notifyDataSetChanged();
//                        integral_sum.setText(0 + "");
                        checkBox_select_all.setChecked(false);
                        toast("删除成功");
                    } else {
                        toast("删除失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    /**
     * 生成订单，结算
     */
    private void doCheckOut() {
        GoodsNumberSerializableMap goodsNumberSerializableMap = new GoodsNumberSerializableMap();
        Map<String, String> goodsNumberMap = new HashMap<>();
        List<ShopCartBean> list = new ArrayList<>();
        List<String> list_id = new ArrayList<>();//商品ID
        for (int i = 0; i < list_data.size(); i++) {
            if (ShopCartAdapter.getIsSelected().get(i)) {
                list.add(list_data.get(i));
                list_id.add(list_data.get(i).getId());
                goodsNumberMap.put(list_data.get(i).getId(), list_data.get(i).getNumber() + "");
            }
            Dlog.e(ShopCartAdapter.getIsSelected().get(i) + "");
        }
        goodsNumberSerializableMap.setMap(goodsNumberMap);
        if (!list.isEmpty() && list.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("goods_list", (Serializable) list);
            bundle.putSerializable("goods_id", (Serializable) list_id);
            bundle.putString("price", price + "");
            bundle.putSerializable("map", goodsNumberSerializableMap);
            overlay(ShoppingCarOrderActivity.class, bundle);
        } else {
            toast("请选择商品");
        }
    }

    //获取集合数据
    private void getListData() {
        showCustomLoadBar(R.string.loading);
        RequestParams parms = new RequestParams(Config.Api.ShopCart_count);
        parms.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
        x.http().post(parms, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                listData = JsonUtils.getInfo(result, "data");
                Dlog.e("GG购物车内容返回数据result" + listData);
                if ("null".equals(listData) || listData == null) {
                    sum = 1;
                    Dlog.e("GG购物车内容返回数据result" + listData);
                }
                if (errCode == 0) {
                    list_data = JSON.parseArray(listData, ShopCartBean.class);
                    Dlog.e("GG购物车数据大小" + list_data.size());
                    if (list_data.size() > 0) {
                        adapter = new ShopCartAdapter(ShoppingCartActivity.this, list_data, handler);
                        sumIntegral = new int[list_data.size() + 1];
                        mListView.setAdapter(adapter);
                    } else {
                        toast(R.string.error_no_info);
                    }
                } else {
                    toast("获取失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });


    }

    double price = 0;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 10) { //更改选中商品的总价格
                price = (double) msg.obj;
                if (price > 0) {
                    integral_sum.setText(price + "");
                } else {
                    integral_sum.setText("0");
                }
            } else if (msg.what == 11) {
                //列表选中状态
                List<Boolean> array = (List<Boolean>) msg.obj;
                if (ShopCartBean.isAllFalse(array)) {
                    checkBox_select_all.setChecked(false);
                }
                if (ShopCartBean.isAllTrue(array)) {
                    checkBox_select_all.setChecked(true);
                }
                if (ShopCartBean.isHaveOneFasle(array)) {
                    checkBox_select_all.setChecked(false);
                }
//                if (ShopCartBean.isHaveOneTrue(array)) {
//                }
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//        int pos = position - 1;
//        ViewHolder viewHolder = (ViewHolder) view.getTag();
//        String num = list_data.get(pos).getNumber();
//        if ("0".equals(num)) {
//            Toast.makeText(context, "请选择商品数量", Toast.LENGTH_LONG).show();
//        } else {
//            boolean cu = !ShopCartAdapter.getIsSelected().get(pos);
//            ShopCartAdapter.getIsSelected().put(pos, cu);
//            adapter.notifyDataSetChanged();
//            //遍历获取列表中checkbox的选中状态
//            HashMap<Integer, Boolean> isSelected = ShopCartAdapter.getIsSelected();
//            Iterator iterator = isSelected.entrySet().iterator();
//            List<Boolean> array = new ArrayList<Boolean>();
//            while (iterator.hasNext()) {
//                HashMap.Entry entry = (HashMap.Entry) iterator.next();
//                Integer key = (Integer) entry.getKey();
//                Boolean val = (Boolean) entry.getValue();
//                array.add(val);
//            }
//            if (ShopCartBean.isAllFalse(array)) {
//                checkBox_select_all.setChecked(false);
//                checkBox_add.setChecked(false);
//            }
//            if (ShopCartBean.isAllTrue(array)) {
//                checkBox_select_all.setChecked(true);
//                checkBox_add.setChecked(true);
//            }
//            if (ShopCartBean.isHaveOneFasle(array)) {
//                checkBox_select_all.setChecked(false);
//            }
//            if (ShopCartBean.isHaveOneTrue(array)) {
//                checkBox_add.setChecked(true);
//            }
//        }
    }
}
